package com.mllweb.api.core.base;


import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 控制器基类
 */
public abstract class BaseController {
    /**
     * 当前Request
     */
    protected HttpServletRequest request;
    /**
     * 当前Response
     */
    protected HttpServletResponse response;
    /**
     * 当前Session
     */
    protected HttpSession session;
    /**
     * 当前Cookie
     */
    protected Cookie[] cookies;
    /**
     * 当前Model
     */
    protected Model model;

    /**
     * 保存请求信息
     *
     * @param request
     * @param response
     * @param model
     */
    @ModelAttribute
    private void modelAttribute(HttpServletRequest request, HttpServletResponse response, Model model) {
        this.request = request;
        this.response = response;
        this.session = request.getSession(true);
        this.cookies = request.getCookies();
        this.model = model;
    }

    /**
     * 跳转到指定错误状态页
     *
     * @param httpStatus
     */
    protected void errorStatus(HttpStatus httpStatus) {
        this.response.setStatus(httpStatus.value());
        String page = "error/" + httpStatus.value();
        try {
            this.request.getRequestDispatcher(page).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重定向到指定URL路径
     *
     * @param url
     * @return
     */
    protected String redirect(String url) {
        return "redirect:" + url;
    }

}